<template>
  <div class="invite-page">
    <header class="invite-header">
      <BrandLogo />
    </header>

    <!-- 接受邀请按钮 -->
    <button class="invite-button" @click="handleInviteAction">{{ buttonText }}</button>

    <!-- 分隔线 -->
    <div class="divider"></div>

    <!-- 使用指南 -->
    <section class="guide-section">
      <h2 class="guide-section__title">Get Started with NearHub Go</h2>

      <div class="guide-content">
        <div class="guide-steps">
          <!-- 步骤 1 -->
          <div class="guide-step">
            <img class="guide-step__icon" referrerpolicy="no-referrer" src="../assets/image/icon/download.png" />
            <div class="guide-step__content">
              <h3 class="guide-step__title">Download app</h3>
              <p class="guide-step__desc">You can download the NearHub Go app and create an account. Don't worry, it's
                free.</p>
            </div>
          </div>

          <!-- 步骤 2 -->
          <div class="guide-step">
            <img class="guide-step__icon" referrerpolicy="no-referrer" src="../assets/image/icon/email.png" />
            <div class="guide-step__content">
              <h3 class="guide-step__title">Accept invite</h3>
              <p class="guide-step__desc">Once you accept the invitation, you will join the photo frame's group the next
                time you log in or register in the app.</p>
            </div>
          </div>

          <!-- 步骤 3 -->
          <div class="guide-step">
            <img class="guide-step__icon" referrerpolicy="no-referrer" src="../assets/image/icon/gallery.png" />
            <div class="guide-step__content">
              <h3 class="guide-step__title">Share memories</h3>
              <p class="guide-step__desc">You can add photos and videos to the frame to share.</p>
            </div>
          </div>
        </div>

        <!-- 图片展示 -->
        <div class="guide-image">
          <img src="../assets/image/computer.png" alt="NearHub Go device" />
        </div>
      </div>
    </section>

    <!-- Toast 组件 -->
    <div class="toast" v-if="toast.show" :class="{ 'toast-error': toast.isError }">
      {{ toast.message }}
    </div>
  </div>
</template>

<script>
import BrandLogo from '@/components/BrandLogo.vue';
import ConstApi from '@/config/api';  // 新增常量导入

export default {
  name: 'InvitePage',
  components: {
    BrandLogo
  },
  data() {
    return {
      constants: {},
      hasToken: false,
      buttonText: 'Join Frame',
      preferences: {
        frameName: '',
        inviter: ''
      },
      toast: {
        show: false,
        message: '',
        isError: false,
        timer: null
      }
    };
  },
  created() {
    // 首先从 localStorage 读取已保存的 preferences
    const savedPreferences = localStorage.getItem('preferences');
    if (savedPreferences) {
      this.preferences = JSON.parse(savedPreferences);
    }

    // 检查 token
    const token = localStorage.getItem('token');
    if (token) {
      this.hasToken = true;
      this.buttonText = 'Join Frame';
    }

    // 从路由参数获取并存储到本地存储
    const { email, teamCode, frameName, inviter } = this.$route.query;
    if (email) localStorage.setItem('userEmail', email);
    if (teamCode) localStorage.setItem('teamCode', teamCode);

    // 只在参数存在时更新 preferences
    if (frameName) this.preferences.frameName = frameName;
    if (inviter) this.preferences.inviter = inviter;

    // 保存到 localStorage
    localStorage.setItem('preferences', JSON.stringify(this.preferences));
  },
  methods: {
    formatEmail(email) {
      if (!email) return { prefix: '', suffix: '' };
      const atIndex = email.lastIndexOf('@');
      if (atIndex === -1) return { prefix: email, suffix: '' };

      const prefix = email.substring(0, atIndex);
      const suffix = email.substring(atIndex);

      // 如果前缀超过12个字符，则截断并添加省略号
      const maxLength = 12;
      const truncatedPrefix = prefix.length > maxLength
        ? prefix.substring(0, maxLength) + '...'
        : prefix;

      return {
        prefix: truncatedPrefix,
        suffix: suffix
      };
    },
    handleInviteAction() {
      if (this.hasToken) {
        this.requestTeamMailActivation();
      } else {
        this.$router.push('/log-in');
      }
    },
    showToast(message, isError = false) {
      // 清除之前的定时器
      if (this.toast.timer) {
        clearTimeout(this.toast.timer);
      }

      // 设置 toast 内容并显示
      this.toast.message = message;
      this.toast.isError = isError;
      this.toast.show = true;

      // 3秒后自动隐藏
      this.toast.timer = setTimeout(() => {
        this.toast.show = false;
      }, 3000);
    },
    async requestTeamMailActivation() {
      try {
        const token = localStorage.getItem('token');
        const email = localStorage.getItem('userEmail') || '';
        const teamCode = localStorage.getItem('teamCode') || '';

        // 构建 GET 请求的 URL 参数
        const params = new URLSearchParams({
          departmentPath: '',
          email: email,
          teamCode: teamCode
        });

        const response = await fetch(
          `${ConstApi.baseUrl}${ConstApi.teamMailActivation}?${params.toString()}`,
          {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              "token": token
            }
          }
        );

        const data = await response.json();

        if (data.code === "0") {
          console.log('Activation successful');
          this.$router.push('/success-page');
        } else {
          console.error('Activation failed:', data.msg);
          this.showToast(`Activation failed: ${data.msg}`, true);
        }
      } catch (error) {
        console.error('API request failed:', error);
        this.showToast('Request failed. Please try again later.', true);
      }
    }
  },
};
</script>

<style scoped>
.invite-page {
  display: flex;
  flex-direction: column;
  max-width: 500px;
  width: 90%;
  margin: 20px auto;
  box-sizing: border-box;
}

/* 页面头部 */
.invite-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.content {
  margin-top: 41px;
  font-size: 18px;
  font-weight: bold;
  font-family: "Helvetica Neue Bold";
  color: #8A69D4;
  text-align: center;
}

.invite-header__title .title-text {
  color: #666666;
  font-size: 20px;
  font-family: HelveticaNeue-Medium;
  font-weight: 500;
}

.invite-header__title .highlight-text {
  color: #7B5AC5;
  font-size: 25px;
  font-family: HelveticaNeue-Bold;
  font-weight: 800;
  display: inline-block;
  margin: 8px 4px;
  letter-spacing: 0.5px;
  text-shadow: 0 1px 2px rgba(123, 90, 197, 0.1);
  transition: all 0.3s ease;
}

.invite-header__title .highlight-text:hover {
  color: #6445B5;
  text-shadow: 0 2px 4px rgba(123, 90, 197, 0.2);
}

.invite-header__title .frame-name {
  margin-top: 8px;
  display: inline-block;
}

/* 框架信息 */
.frame-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 30px;
  margin-top: 42px;
  box-sizing: border-box;
}

.frame-info__item {
  flex: 1;
}

.frame-info__item:first-child {
  text-align: left;
}

.frame-info__item:last-child {
  text-align: right;
}

.frame-info__label {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  font-family: HelveticaNeue-Medium;
  font-weight: 500;
  line-height: 17px;
}

.frame-info__value {
  color: rgba(51, 51, 51, 1);
  font-size: 14px;
  font-family: HelveticaNeue-Medium;
  font-weight: 500;
  line-height: 17px;
  margin-top: 4px;
}

/* 接受邀请按钮 */
.invite-button {
  background-color: rgba(138, 105, 212, 1);
  border: none;
  border-radius: 8px;
  color: rgba(255, 255, 255, 1);
  font-size: 18px;
  font-family: HelveticaNeue-Medium;
  font-weight: 500;
  text-align: center;
  line-height: 23px;
  padding: 11px 0 13px;
  margin: 30px 30px 0;
  width: calc(100% - 60px);
  cursor: pointer;
}

/* 分隔线 */
.divider {
  width: 100%;
  max-width: 335px;
  height: 1px;
  background-color: #e0e0e0;
  margin: 40px auto 0;
}

/* 使用指南 */
.guide-section {
  margin-top: 20px;
}

.guide-section__title {
  color: rgba(51, 51, 51, 1);
  font-size: 20px;
  font-family: HelveticaNeue-Bold;
  font-weight: 700;
  text-align: center;
  line-height: 23px;
  margin-bottom: 42px;
}

.guide-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  position: relative;
}

.guide-steps {
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  margin-right: 10%;
}

.guide-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 42px;
}

.guide-step:last-child {
  margin-bottom: 0;
}

.guide-step__icon {
  width: auto;
  height: auto;
  max-width: 39px;
  max-height: 39px;
}

.guide-step__content {
  text-align: center;
}

.guide-step__title {
  color: rgba(138, 105, 212, 1);
  font-size: 16px;
  font-family: HelveticaNeue-Bold;
  font-weight: 700;
  line-height: 17px;
}

.guide-step__desc {
  max-width: 140px;
  width: 100%;
  color: rgba(51, 51, 51, 1);
  font-size: 13px;
  font-family: HelveticaNeue;
  font-weight: normal;
  text-align: center;
  line-height: 16px;
}

.guide-image {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  overflow: hidden;
  margin-left: auto;
}

.guide-image img {
  width: auto;
  max-width: 100%;
  height: auto;
  margin-top: 230px;
}

/* Toast 样式 */
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #4CAF50;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
  font-family: HelveticaNeue-Medium;
}

.toast-error {
  background-color: #F44336;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }

  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translate(-50%, 0);
  }

  to {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
}
</style>